package test.wordprj.word.uitl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.BorderStyle;
import test.wordprj.word.bean.MenuExcelModel;
import test.wordprj.word.bean.MenuNode;

import java.util.List;

public class ExcelExporter {
    public static void export(String fileName, List<MenuNode> treeData) {
        // 1. 平铺树形数据
        List<MenuExcelModel> data = TreeDataFlatter.convert(treeData);


        // 2. 配置写入参数
        ExcelWriter excelWriter = EasyExcel.write(fileName, MenuExcelModel.class)
                .registerWriteHandler(new TreeCellMergeStrategy()) // 注册合并策略
                .registerWriteHandler(new HorizontalCellStyleStrategy()) // 样式策略
                .registerWriteHandler(getHorizontalCellStyleStrategy())
                .build();


        // 3. 写入数据
        WriteSheet writeSheet = EasyExcel.writerSheet("菜单结构").build();
        excelWriter.write(data, writeSheet);


        // 4. 关闭流
        excelWriter.finish();
    }

    /**
     * 设置单元格样式
     *
     * @return HorizontalCellStyleStrategy
     */
    private static HorizontalCellStyleStrategy getHorizontalCellStyleStrategy() {
        // 设置边框样式
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();

        // 设置边框
        BorderStyle borderStyle = BorderStyle.THIN;
        headWriteCellStyle.setBorderTop(borderStyle);
        headWriteCellStyle.setBorderBottom(borderStyle);
        headWriteCellStyle.setBorderLeft(borderStyle);
        headWriteCellStyle.setBorderRight(borderStyle);

        contentWriteCellStyle.setBorderTop(borderStyle);
        contentWriteCellStyle.setBorderBottom(borderStyle);
        contentWriteCellStyle.setBorderLeft(borderStyle);
        contentWriteCellStyle.setBorderRight(borderStyle);

        // 创建水平样式策略
        return new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
    }
}
